local JsonParser = {
    json_file = "",
}

local log = require "log"
local cjson = require "cjson"
-- 增加缓存，减少频繁打开关闭文件, key为文件名, value为文件内容
local JsonCache = {}

function JsonParser:new(o, json_file, default_file)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    self.json_file = json_file..".json"
    self.json_flag = json_file..".flag"
    self.default_file = default_file
    self.file_key = string.sub(json_file, 19)
    return o
end

function JsonParser:read_file()
    -- json_flag文件存在，则说明json文件被外部修改，需要重读
    local json_modify = io.open(self.json_flag, "rb")
    -- 缓存里如果没有此文件，才打开文件读
    if JsonCache[self.file_key] == nil or json_modify then
        local file, error_info = io.open(self.json_file, "r")
        if file == nil then
            file, error_info = io.open(self.default_file, "r")
            if file == nil then
                log:print(LOG_ERROR, "open file(%s) fail, %s", self.default_file, error_info)
                return false
            end
        end
        log:print(LOG_ERROR, "open json: %s, key: %s", self.json_file, self.file_key)
        local str = file:read("*a")
        log:print(LOG_DEBUG, str)
        file:close()
        JsonCache[self.file_key] = str
		
        if json_modify then
            os.remove(self.json_flag)
            log:print(LOG_ERROR, "delete json_flag: %s", self.json_flag)
        end
        return true, str
    else
        log:print(LOG_DEBUG, "json cache: %s", self.json_file)
        return true, JsonCache[self.file_key]
    end
end

function JsonParser:parse()
    local ret, str = self:read_file()
    if ret then
        self.op_table = cjson.decode(str)
    end
    return ret
end

function JsonParser:get_value(key)
    if self.op_table == nil then
        local ret = self:parse()
        if ret ~= true then
            log:print(LOG_DEBUG, "get value of key(%s) error", key)
            return
        end
    end
    return self.op_table[key]
end

function JsonParser:set_value(key, value)
    if self.op_table == nil then
        local ret = self:parse()
        if ret ~= true then
            return
        end
    end
    self.op_table[key] = value
end

function JsonParser:write_file()
    local str = cjson.encode(self.op_table)
    local file = io.open(self.json_file, "w")
    if file == nil then
        log:print(LOG_ERROR, "write_file open fiel fail")
        return
    end
    file:write(str)
    file:close()

    JsonCache[self.file_key] = str
end

return JsonParser
